<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
      class="query-params-form"
    >
      <el-form-item label="字段编码" prop="fieldNumber">
        <el-input
          v-model="queryParams.fieldNumber"
          placeholder="请输入字段编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="显示名称" prop="displayName">
        <el-input
          v-model="queryParams.displayName"
          placeholder="请输入显示名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="固定值" prop="fixedValue">
        <el-input
          v-model="queryParams.fixedValue"
          placeholder="请输入固定值"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAddPageFieldLine"
          >添加</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          @click="handleDeletePageFieldLine"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Document" @click="submitTable"
          >保存</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Close" @click="handleClose"
          >关闭</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <el-table
      :data="pagefieldList"
      @selection-change="handlePagefieldLineSelectionChange"
      ref="pagefieldLine"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="序号" type="index" width="50" />
      <!-- <el-table-column label="页面ID" prop="pageId" width="120">
        <template #default="scope">
          <el-input v-model="scope.row.pageId" placeholder="请选择页面" />
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="字段ID" prop="fieldId" width="120">
        <template #default="scope">
          <el-input v-model="scope.row.fieldId" placeholder="请选择字段" />
        </template>
      </el-table-column> -->
      <el-table-column label="字段编码" prop="fieldNumber" width="120">
      </el-table-column>
      <el-table-column label="显示名称" prop="displayName" width="120">
        <template #default="scope">
          <el-input
            v-model="scope.row.displayName"
            placeholder="请输入显示名称"
          />
        </template>
      </el-table-column>
      <el-table-column label="宽度" prop="width" width="120">
        <template #default="scope">
          <el-input v-model="scope.row.width" placeholder="请输入宽度" />
        </template>
      </el-table-column>
      <el-table-column label="高度" prop="height" width="120">
        <template #default="scope">
          <el-input v-model="scope.row.height" placeholder="请输入高度" />
        </template>
      </el-table-column>
      <el-table-column
        label="是否匹配"
        prop="isMatched"
        width="80"
        align="center"
      >
        <template #default="scope">
          <el-checkbox
            :true-label="1"
            :false-label="0"
            v-model="scope.row.isMatched"
          ></el-checkbox>
        </template>
      </el-table-column>

      <el-table-column
        label="是否必填"
        prop="isRequired"
        width="80"
        align="center"
      >
        <template #default="scope">
          <el-checkbox
            :true-label="1"
            :false-label="0"
            v-model="scope.row.isRequired"
          ></el-checkbox>
        </template>
      </el-table-column>

      <el-table-column label="固定值" prop="fixedValue" width="120">
        <template #default="scope">
          <el-input v-model="scope.row.fixedValue" placeholder="" />
        </template>
      </el-table-column>

      <el-table-column
        label="源单显示"
        prop="sourceDisplay"
        width="80"
        align="center"
      >
        <template #default="scope">
          <el-checkbox
            :true-label="1"
            :false-label="0"
            v-model="scope.row.sourceDisplay"
          ></el-checkbox>
        </template>
      </el-table-column>

      <el-table-column
        label="操作显示"
        prop="operationDisplay"
        width="80"
        align="center"
      >
        <template #default="scope">
          <el-checkbox
            :true-label="1"
            :false-label="0"
            v-model="scope.row.operationDisplay"
          ></el-checkbox>
        </template>
      </el-table-column>

      <el-table-column
        label="查询显示"
        prop="queryDisplay"
        width="80"
        align="center"
      >
        <template #default="scope">
          <el-checkbox
            :true-label="1"
            :false-label="0"
            v-model="scope.row.queryDisplay"
          ></el-checkbox>
        </template>
      </el-table-column>

      <el-table-column
        label="草稿显示"
        prop="draftDisplay"
        width="80"
        align="center"
      >
        <template #default="scope">
          <el-checkbox
            :true-label="1"
            :false-label="0"
            v-model="scope.row.draftDisplay"
          ></el-checkbox>
        </template>
      </el-table-column>

      <el-table-column label="源单排序" prop="sourceOrder">
        <template #default="scope">
          <el-input v-model="scope.row.sourceOrder" placeholder="" />
          <!-- <el-input-number v-model="scope.row.sourceOrder" controls-position="right" :min="0" width="50" /> -->
        </template>
      </el-table-column>

      <el-table-column label="操作排序" prop="operationOrder">
        <template #default="scope">
          <el-input v-model="scope.row.operationOrder" placeholder="" />
          <!-- <el-input-number v-model="scope.row.operationOrder" controls-position="right" :min="0" /> -->
        </template>
      </el-table-column>

      <el-table-column label="查询排序" prop="queryOrder">
        <template #default="scope">
          <el-input v-model="scope.row.queryOrder" placeholder="" />
          <!-- <el-input-number v-model="scope.row.queryOrder" controls-position="right" :min="0" /> -->
        </template>
      </el-table-column>

      <el-table-column label="草稿排序" prop="draftOrder">
        <template #default="scope">
          <el-input v-model="scope.row.draftOrder" placeholder="" />
          <!-- <el-input-number v-model="scope.row.draftOrder" controls-position="right" :min="0" /> -->
        </template>
      </el-table-column>

      <el-table-column
        label="操作弹框查询"
        prop="operationPopupQuery"
        width="80"
        align="center"
      >
        <template #default="scope">
          <el-checkbox
            :true-label="1"
            :false-label="0"
            v-model="scope.row.operationPopupQuery"
          ></el-checkbox>
        </template>
      </el-table-column>

      <el-table-column
        label="草稿弹框查询"
        prop="draftPopupQuery"
        width="80"
        align="center"
      >
        <template #default="scope">
          <el-checkbox
            :true-label="1"
            :false-label="0"
            v-model="scope.row.draftPopupQuery"
          ></el-checkbox>
        </template>
      </el-table-column>

      <el-table-column label="接口传参" prop="interfaceParameter">
        <template #default="scope">
          <el-input
            v-model="scope.row.interfaceParameter"
            placeholder="请选择传参接口"
          />
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改条码页面字段映射对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="pagefieldRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="页面ID" prop="pageId">
          <el-input v-model="form.pageId" placeholder="请输入页面ID" />
        </el-form-item>
        <el-form-item label="字段ID" prop="fieldId">
          <el-input v-model="form.fieldId" placeholder="请输入字段ID" />
        </el-form-item>
        <el-form-item label="字段编码" prop="fieldNumber">
          <el-input v-model="form.fieldNumber" placeholder="请输入字段编码" />
        </el-form-item>
        <el-form-item label="显示名称" prop="displayName">
          <el-input v-model="form.displayName" placeholder="请输入显示名称" />
        </el-form-item>
        <el-form-item label="宽度" prop="width">
          <el-input v-model="form.width" placeholder="请输入宽度" />
        </el-form-item>
        <el-form-item label="高度" prop="height">
          <el-input v-model="form.height" placeholder="请输入高度" />
        </el-form-item>
        <el-form-item label="固定值" prop="fixedValue">
          <el-input v-model="form.fixedValue" placeholder="请输入固定值" />
        </el-form-item>
        <el-form-item label="接口传参" prop="interfaceParameter">
          <el-input
            v-model="form.interfaceParameter"
            placeholder="请输入接口传参"
          />
        </el-form-item>
        <el-form-item label="源单显示" prop="sourceDisplay">
          <el-input v-model="form.sourceDisplay" placeholder="请输入源单显示" />
        </el-form-item>
        <el-form-item label="源单排序" prop="sourceOrder">
          <el-input v-model="form.sourceOrder" placeholder="请输入源单排序" />
        </el-form-item>
        <el-form-item label="操作排序" prop="operationOrder">
          <el-input
            v-model="form.operationOrder"
            placeholder="请输入操作排序"
          />
        </el-form-item>
        <el-form-item label="查询排序" prop="queryOrder">
          <el-input v-model="form.queryOrder" placeholder="请输入查询排序" />
        </el-form-item>
        <el-form-item label="草稿排序" prop="draftOrder">
          <el-input v-model="form.draftOrder" placeholder="请输入草稿排序" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <select-field ref="selectFieldRef" @ok="handleImportField" />
  </div>
</template>

<script setup name="Pagefield">
import {
  listPagefield,
  getPagefield,
  delPagefield,
  addPagefield,
  updatePagefield,
  savePagefield,
} from "@/api/barcode/pagefield";

import selectField from "@/views/barcode/field/select.vue";

const { proxy } = getCurrentInstance();
const route = useRoute();

const pagefieldList = ref([]);
const checkedPagefieldList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    fieldNumber: null,
    displayName: null,
    isMatched: null,
    isRequired: null,
    fixedValue: null,
  },
  rules: {
    id: [{ required: true, message: " 不能为空", trigger: "blur" }],
    pageId: [{ required: true, message: "页面ID不能为空", trigger: "blur" }],
    fieldId: [{ required: true, message: "字段ID不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询条码页面字段映射列表 */
function getList() {
  loading.value = true;
  queryParams.value.pageId = route.params && route.params.id;
  listPagefield(queryParams.value).then((response) => {
    pagefieldList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    pageId: null,
    fieldId: null,
    fieldNumber: null,
    displayName: null,
    width: null,
    height: null,
    isMatched: null,
    isRequired: null,
    fixedValue: null,
    interfaceParameter: null,
    sourceDisplay: null,
    sourceOrder: null,
    operationDisplay: null,
    operationOrder: null,
    operationPopupQuery: null,
    queryDisplay: null,
    queryOrder: null,
    draftDisplay: null,
    draftOrder: null,
    draftPopupQuery: null,
    createdDate: null,
    createdBy: null,
    modifiedDate: null,
    modifiedBy: null,
  };
  proxy.resetForm("pagefieldRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

function handlecheckedPagefieldSelectionChange(selection) {
  checkedBarcodeFieldLine.value = selection.map((item) => item.index);
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加条码页面字段映射";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getPagefield(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改条码页面字段映射";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["pagefieldRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updatePagefield(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        form.value.pageId = route.params && route.params.id;
        addPagefield(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除条码页面字段映射编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delPagefield(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

function handleAddPageFieldLine() {
  proxy.$refs["selectFieldRef"].show();
}

function handleDeletePageFieldLine() {
  if (checkedPagefieldList.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的条码字段行数据");
  } else {
    const barcodeFieldLines = pagefieldList.value;
    const checkedPagefieldLists = checkedPagefieldList.value;
    pagefieldList.value = barcodeFieldLines.filter(function (item) {
      return checkedPagefieldLists.indexOf(item.id) == -1;
    });
  }
}

/** 复选框选中数据 */
function handlePagefieldLineSelectionChange(selection) {
  checkedPagefieldList.value = selection.map((item) => item.id);
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "barcode/pagefield/export",
    {
      ...queryParams.value,
    },
    `pagefield_${new Date().getTime()}.xlsx`
  );
}

function submitTable() {
  const _pid = route.params && route.params.id;
  const _pageFieldList = pagefieldList.value.map((item) => {
    return toRaw(item);
  });
  const _params = {
    id: _pid,
    pageFieldMappingList: _pageFieldList,
  };
  console.log("_params", _params);
  savePagefield(_params).then((response) => {
    proxy.$modal.msgSuccess("保存成功");
    open.value = false;
    getList();
  });
}

/** 返回按钮操作 */
function handleClose() {
  const obj = { path: "/barcode/page" };
  proxy.$tab.closeOpenPage(obj);
}

function handleImportField(selectedRow) {
  console.log("handleImportField", selectedRow);
  // const _fids = selectedRow.map((x) => x.id);
  // if (pagefieldList.value.some((x) => _fids.includes(x.fieldId))) {
  //   proxy.$modal.msgError("该条码字段已存在");
  //   return;
  // }

  const errmsgs = [];

  pagefieldList.value.forEach((el) => {
    const _f = selectedRow.find((x) => x.id == el.fieldId);
    if (_f !== undefined) {
      errmsgs.push(_f.code + "-" + _f.name);
    }
  });

  if (errmsgs.length > 0) {
    proxy.$modal.msgError(`该条码字段已存在:${errmsgs.join(",")}`);
    return;
  }

  for (let i = 0; i < selectedRow.length; i++) {
    const _fieldRow = selectedRow[i];
    let obj = {};
    obj.id = pagefieldList.value.length + 1;
    obj.fieldId = _fieldRow.id;
    obj.fieldNumber = _fieldRow.code;
    obj.displayName = _fieldRow.name;
    obj.width = 1;
    obj.height = 24;
    obj.isMatched = 0;
    obj.isRequired = 0;
    obj.fixedValue = "";
    obj.interfaceParameter = "";
    obj.sourceDisplay = 1;
    obj.sourceOrder = 0;
    obj.operationDisplay = 1;
    obj.operationOrder = 0;
    obj.operationPopupQuery = 0;
    obj.queryDisplay = 1;
    obj.queryOrder = 0;
    obj.draftDisplay = 1;
    obj.draftOrder = 0;
    obj.draftPopupQuery = 0;
    pagefieldList.value.push(obj);
  }

  proxy.$refs["selectFieldRef"].hide();
}

getList();
</script>
